<?php
require_once('gbif.checklist.php');
class Checklist13 extends Checklist {

	function __construct( $file = NULL ) {
		parent::__construct($file);
	}

	public function validateChecklistData( $sheetIndex = 2 ) {
		if (!$this->fileOpen) $this->openFile();

		$passed = true;
		$wk = $this->objPHPExcel->setActiveSheetIndex( $sheetIndex );

		$highestRow = $wk->getHighestRow();
		$highestColumn = $wk->getHighestColumn();
		$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);

		$rowIndex = -1;
		# Builds array but removes any blank rows
		foreach ($wk->getRowIterator() as $row) {
			$rowIndex++;
			$blankRow = true;

			$cellIterator = $row->getCellIterator();
 			$cellIterator->setIterateOnlyExistingCells(false);
#			$cellIterator->setIterateOnlyExistingCells(true);
			$colIndex = -1;

			foreach ($cellIterator as $cell) {
				$colIndex++;
				$value = $cell->getValue(); // Removed utf8_decode() for unicode compatibility. bko@GBIFS on 12 Dec 11.

				# Check that data do not contain control characters that break the XML transfer format (e.g. vertical tabs).  Remove if included.
				$value = str_replace("\x0B", '', $value);  //remove all vertical tabs in sender string
#ADD MORE CONDITIONS
				$this->checklistArray[$rowIndex][$colIndex] = trim($value);
				if ($this->checklistArray[$rowIndex][$colIndex] != '') {
					$blankRow = false;
				}
			}

			if ($blankRow || $rowIndex == 0) {
				// Clean blank empty rows
				unset($this->checklistArray[$rowIndex]);
			} else {
				if ($rowIndex > 0) {
					$tmpObj->kingdom = $this->checklistArray[$rowIndex][0];
					$tmpObj->phylum = $this->checklistArray[$rowIndex][1];
					$tmpObj->subphylum = $this->checklistArray[$rowIndex][2];
					$tmpObj->class = $this->checklistArray[$rowIndex][3];
					$tmpObj->order = $this->checklistArray[$rowIndex][4];
					$tmpObj->family = $this->checklistArray[$rowIndex][5];
					$tmpObj->genus = $this->checklistArray[$rowIndex][6];
					$tmpObj->species = $this->checklistArray[$rowIndex][7];
					$tmpObj->author = $this->checklistArray[$rowIndex][8];

					$this->addTaxa( $tmpObj );
				}
			}
		}

/*
		$this->header = array_shift($this->checklistArray);
		# Check for the presence and sequence of all column headers in order to generate the proper meta.xml file
		for($i=0; $i<=count($this->checklistHeaderList); $i++) {
			if ($this->header[$i+1] != $this->checklistHeaderList[$i]) {
				$this->addError('MandatoryElement', 203, sprintf('Header columns do not match '%s' != '%s'', $this->header[$i+1], $this->checklistHeaderList[$i]) );
				$passed = false;
			}
		}

#			for ($i=1; $i<= count($this->checklistArray); $i++) {
		for ($i=1; $i<= 1; $i++) {
			$row = $this->checklistArray[$i-1];

			# Mandatory elements are
			$mandatoryArray = array(
					'0' => 'taxonID'
			);
			
			foreach($mandatoryArray as $key => $value) {
#					print $key . $value . ' $row[$key]<br>';
				if ($row[$key] == '') {
					$this->addError('MandatoryElement', 200, '$value not found on row: $i' );
					$passed = false;
				}
			}

		}
*/
		return( $passed );
	}

	public function writechecklistData($path = '') {
		$fp = fopen($path . $this->checklistFilename, 'w');
		fputs($fp, "\xEF\xBB\xBF"); 		
		fputcsv($fp, $this->checklistOutputHeaderList );

		$fpVernacular = fopen( $path . $this->vernacularFilename, 'w');
		fputs($fpVernacular, "\xEF\xBB\xBF"); 
		fputcsv($fpVernacular, $this->vernacularHeaderList);

		$fpDistribution = fopen( $path . $this->distributionFilename, 'w');
		fputs($fpDistribution, "\xEF\xBB\xBF"); 
		fputcsv($fpDistribution, $this->distributionHeaderList);

		if(is_array($this->taxa)) {
		foreach($this->taxa as $rec) {
			fputcsv($fp, array(
					$rec['index']
				,	$this->taxa[$rec['parent']]['index']
				,	""
				,	$rec['value']
				,	$rec['authorship']
				,	""
				,	$rec['rank']
			));
		}
		}

		if(is_array($this->checklistArray)) {
		foreach ($this->checklistArray as $row) {

			// Lookup Parent ID
			$parent = $this->taxa[ $row[6] . $row[5] . $row[4] . $row[3] . $row[2] . $row[1] . $row[0] ];

			$infraRanks = array("ssp. ", "ssp ", "var. ", "var ");
			$tmpRank = "species";

			foreach($infraRanks as $infraRank) {
				$pos = stripos($row[7], $infraRank);
				if($pos === false) {
					// infraspecies NOT found
				} else {
					$tmpRank = "infraspecies";
					break;
				}
			}

			# if species exist in cell 7 then save species info
			if ($row[7] != '') {
				$tmpSpecies = array(
						"sp" . $this->speciesIndex++
					,	$parent["index"]
					,	""
					,	$row[7]
					,	$row[8]
					,	$row[11]
					,	$tmpRank
					,	""
					,	$row[16]
				);
				
				// Write species to file
				fputcsv($fp, $tmpSpecies );

				// This adds synonyms after the species row.
				$this->writeSynonymData($fp, "sp" . ($this->speciesIndex - 1), $row[9]);
			}

			// If common name exists send to vernacular file to be added
			if ($row[10] != "") {
				$tmpIndex = $parent["index"];
				if ($row[7] != "") {
					$tmpIndex = "sp" . ($this->speciesIndex - 1);
				}
					
				$this->writeVernacularData($fpVernacular, $tmpIndex, $row[10]);
			}

			// If Distribution names exist send to file to be added
			if ((trim($row[12]) != '') 
				|| (trim($row[13]) != '')
				|| (trim($row[14]) != '')
				|| (trim($row[15]) != '')
			){
				$this->writeDistributionData($fpDistribution, "sp" . ($this->speciesIndex - 1), array('countries' => $row[12], 'delimiter' => '|'), $row[13], $row[14], $row[15] );
			}

		} # foreach checklist row
		}
			
		fclose($fp);
		fclose($fpVernacular);
	}

	public function addTaxa( $rec ) {
		static $index = 1;
		$parent = '';
		if ($rec->kingdom != '') {
			if (!isset( $this->taxa[$rec->kingdom] ) ) {
				$this->taxa[ $rec->kingdom ] = array(
						'rank' => 'kingdom'
					,	'parent' => $parent
					,	'value' => $rec->kingdom
					,	'index' => $index++
				);
			}
		}

		$parent = $rec->kingdom . $parent;
		if ($rec->phylum != '') {
			if (!isset( $this->taxa[$rec->phylum . $parent] ) ) {
				$this->taxa[ $rec->phylum . $parent ] = array(
						'rank' => 'phylum'
					,	'parent' => $parent
					,	'value' => $rec->phylum
					,	'index' => $index++
				);
			}
		}

		$parent = $rec->phylum . $parent;
		if ($rec->subphylum != '') {
			if (!isset( $this->taxa[$rec->subphylum . $parent] ) ) {
				$this->taxa[ $rec->subphylum . $parent ] = array(
						'rank' => 'subphylum'
					,	'parent' => $parent
					,	'value' => $rec->subphylum
					,	'index' => $index++
				);
			}
		}

		$parent = $rec->subphylum . $parent;
		if ($rec->class != '') {
			if (!isset( $this->taxa[$rec->class . $parent] ) ) {
				$this->taxa[ $rec->class . $parent ] = array(
						'rank' => 'class'
					,	'parent' => $parent
					,	'value' => $rec->class
					,	'index' => $index++
				);
			}
		}

		$parent = $rec->class . $parent;
		if ($rec->order != '') {
			if (!isset( $this->taxa[$rec->order . $parent] ) ) {
				$this->taxa[ $rec->order . $parent ] = array(
						'rank' => 'order'
					,	'parent' => $parent
					,	'value' => $rec->order
					,	'index' => $index++
				);
			}
		}

		$parent = $rec->order . $parent;
		if ($rec->family != '') {
			if (!isset( $this->taxa[$rec->family . $parent] ) ) {
				$this->taxa[ $rec->family . $parent ] = array(
						'rank' => 'family'
					,	'parent' => $parent
					,	'value' => $rec->family
					,	'index' => $index++
				);
			}
		}

		$parent = $rec->family . $parent;
		if ($rec->genus != '') {
			if (!isset( $this->taxa[$rec->genus . $parent] ) ) {
				$this->taxa[ $rec->genus . $parent ] = array(
						'rank' => 'genus'
					,	'parent' => $parent
					,	'value' => $rec->genus
					,	'index' => $index++
				);
			}
		}

	}

}
?>